<template>
  <div class="divBox relative">
    <el-card class="box-card">
      <div class="clearfix">
        <div class="container">
          <el-form size="small" label-width="100px">
            <el-form-item :label="$t('dingDanZhuangTai') + '：'" v-if="checkPermi(['admin:order:status:num'])">
              <el-radio-group v-model="tableFrom.status" type="button" @change="seachList">
                <el-radio-button label="all"
                  >{{ $t('quanBu') }} {{ '(' + orderChartType.all ? orderChartType.all : 0 + ')' }}
                </el-radio-button>
                <el-radio-button label="unPaid"
                  >{{ $t('weiZhiFu') }} {{ '(' + orderChartType.unPaid ? orderChartType.unPaid : 0 + ')' }}
                </el-radio-button>
                <el-radio-button label="notShipped"
                  >{{ $t('weiFaHuo') }} {{ '(' + orderChartType.notShipped ? orderChartType.notShipped : 0 + ')' }}
                </el-radio-button>
                <el-radio-button label="spike"
                  >{{ $t('daiShouHuo') }} {{ '(' + orderChartType.spike ? orderChartType.spike : 0 + ')' }}
                </el-radio-button>
                <el-radio-button label="complete"
                  >{{ $t('jiaoYiWanCheng') }} {{ '(' + orderChartType.complete ? orderChartType.complete : 0 + ')' }}
                </el-radio-button>
                <el-radio-button label="refunded"
                  >{{ $t('yiTuiKuan') }} {{ '(' + orderChartType.refunded ? orderChartType.refunded : 0 + ')' }}
                </el-radio-button>
                <el-radio-button label="deleted"
                  >{{ $t('yiShanChu') }} {{ '(' + orderChartType.deleted ? orderChartType.deleted : 0 + ')' }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="$t('shiJianXuanZe') + '：'" class="width100">
              <el-radio-group
                v-model="tableFrom.dateLimit"
                type="button"
                class="mr20"
                size="small"
                @change="selectChange(tableFrom.dateLimit)"
              >
                <el-radio-button v-for="(item, i) in fromList.fromTxt" :key="i" :label="item.val"
                  >{{ item.text }}
                </el-radio-button>
              </el-radio-group>
              <el-date-picker
                v-model="timeVal"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                size="small"
                type="daterange"
                placement="bottom-end"
                :placeholder="$t('ziDingYiShiJian')"
                style="width: 220px"
                @change="onchangeTime"
              />
            </el-form-item>
            <el-form-item :label="$t('dingDanHao') + '：'" class="width100">
              <el-input
                v-model="tableFrom.orderNo"
                :placeholder="$t('qingShuRuDingDanHao')"
                class="selWidth"
                size="small"
                clearable
              >
                <el-button slot="append" icon="el-icon-search" size="small" @click="seachList" />
              </el-input>
            </el-form-item>
            <!--<el-form-item class="width100">-->
            <!--<el-button size="small" @click="exports" v-hasPermi="['admin:export:excel:order']">导出</el-button>-->
            <!--</el-form-item>-->
          </el-form>
        </div>
      </div>
    </el-card>
    <div class="mt20">
      <!-- <cards-data :cardLists="cardLists" v-if="checkPermi(['admin:order:list:data'])"></cards-data> -->
    </div>
    <el-card class="box-card">
      <el-table
        v-loading="listLoading"
        :data="tableData.data"
        size="mini"
        class="table"
        highlight-current-row
        :header-cell-style="{ fontWeight: 'bold' }"
        :row-key="
          (row) => {
            return row.orderNo;
          }
        "
      >
        <!-- @selection-change="handleSelectionChange" -->
        <!-- <el-table-column
          type="selection"
          :reserve-selection="true"
          width="55"
        /> -->
        <el-table-column :label="$t('dingDanHao')" min-width="185" v-if="checkedCities.includes('dingDanHao')">
          <template slot-scope="scope">
            <span
              style="display: block"
              :class="scope.row.refundStatus === 1 || scope.row.refundStatus === 3 ? 'red' : ''"
              v-text="scope.row.orderNo"
            />
            <span v-show="scope.row.isUserDel" style="color: #ed4014; display: block">{{ $t('yongHuYiShanChu') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="masterOrderNo"
          :label="$t('zhuDingDanHao')"
          min-width="180"
          v-if="checkedCities.includes('zhuDingDanHao')"
        />
        <!--prop="orderType"-->
        <!--label="订单状态"-->
        <!--min-width="110"-->
        <!--v-if="checkedCities.includes('订单状态')"-->
        <el-table-column
          prop="realName"
          :label="$t('shouHuoRen')"
          min-width="100"
          v-if="checkedCities.includes('shouHuoRen')"
        />
        <el-table-column
          prop="payPrice"
          :label="$t('shiJiZhiFu')"
          min-width="80"
          v-if="checkedCities.includes('shiJiZhiFu')"
        />
        <el-table-column :label="$t('zhiFuFangShi')" min-width="80" v-if="checkedCities.includes('zhiFuFangShi')">
          <template slot-scope="scope">
            <span>{{ scope.row.payType }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('dingDanZhuangTai')"
          min-width="100"
          v-if="checkedCities.includes('dingDanZhuangTai')"
        >
          <template slot-scope="scope">
            <span v-show="scope.row.isUserDel">{{ $t('yiShanChu') }}</span>
            <span v-show="scope.row.refundStatus === 3">{{ $t('yiTuiKuan') }}</span>
            <span v-show="scope.row.paid === false && scope.row.status === 0">{{ $t('weiZhiFu') }}</span>
            <span v-show="scope.row.status === 0">{{ $t('weiFaHuo') }}</span>
            <span v-show="scope.row.status === 1">{{ $t('daiShouHuo') }}</span>
            <span v-show="scope.row.status === 3">{{ $t('yiWanCheng') }}</span>
            <span v-show="scope.row.status === 9">{{ $t('yiQuXiao') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('pingTaiBeiZhu')"
          min-width="120"
          :show-overflow-tooltip="true"
          v-if="checkedCities.includes('pingTaiBeiZhu')"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.platformRemark | filterEmpty }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('shangJiaBeiZhu')"
          min-width="120"
          :show-overflow-tooltip="true"
          v-if="checkedCities.includes('shangJiaBeiZhu')"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.merRemark | filterEmpty }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          :label="$t('xiaDanShiJian')"
          min-width="150"
          v-if="checkedCities.includes('xiaDanShiJian')"
        />
        <el-table-column
          :label="$t('caoZuo')"
          min-width="150"
          fixed="right"
          align="center"
          :render-header="renderHeader"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click.native="onOrderDetails(scope.row.orderNo)"
              v-hasPermi="['platform:order:info']"
              >{{ $t('dingDanXiangQing') }}</el-button
            >
            <el-button
              type="text"
              size="small"
              @click.native="onOrderMark(scope.row)"
              v-hasPermi="['platform:order:mark']"
              >{{ $t('dingDanBeiZhu') }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[20, 40, 60, 80]"
          :page-size="tableFrom.limit"
          :current-page="tableFrom.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>
    <div class="card_abs" v-show="card_select_show">
      <template>
        <div class="cell_ht">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">{{
            $t('quanXuan')
          }}</el-checkbox>
          <el-button type="text" @click="checkSave()">{{ $t('baoCun') }}</el-button>
        </div>
        <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="item in columnData" :label="item" :key="item" class="check_cell">{{ item }}</el-checkbox>
        </el-checkbox-group>
      </template>
    </div>
    <!--编辑-->
    <el-dialog :title="$t('bianJiDingDan')" :visible.sync="dialogVisible" width="500px" :before-close="handleClose">
      <z-b-parser
        v-if="dialogVisible"
        :form-id="104"
        :is-create="isCreate"
        :edit-data="editData"
        @submit="handlerSubmit"
        @resetForm="resetForm"
      />
    </el-dialog>

    <!--记录-->
    <el-dialog :title="$t('caoZuoJiLu')" :visible.sync="dialogVisibleJI" width="700px">
      <el-table v-loading="LogLoading" border :data="tableDataLog.data" style="width: 100%">
        <el-table-column prop="oid" align="center" label="ID" min-width="80" />
        <el-table-column prop="changeMessage" :label="$t('caoZuoJiLu')" align="center" min-width="280" />
        <el-table-column prop="createTime" :label="$t('caoZuoShiJian')" align="center" min-width="280" />
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[10, 20, 30, 40]"
          :page-size="tableFromLog.limit"
          :current-page="tableFromLog.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableDataLog.total"
          @size-change="handleSizeChangeLog"
          @current-change="pageChangeLog"
        />
      </div>
    </el-dialog>

    <!--详情-->
    <details-from ref="orderDetail" :orderId="orderId" />

    <!--拒绝退款-->
    <el-dialog
      :title="$t('juJueTuiKuanYuanYin')"
      v-if="RefuseVisible"
      :visible.sync="RefuseVisible"
      width="500px"
      :before-close="RefusehandleClose"
    >
      <z-b-parser
        :form-id="106"
        :is-create="1"
        :edit-data="RefuseData"
        @submit="RefusehandlerSubmit"
        @resetForm="resetFormRefusehand"
      />
    </el-dialog>

    <!--立即退款-->
    <el-dialog
      :title="$t('tuiKuanChuLi')"
      :visible.sync="refundVisible"
      width="500px"
      :before-close="refundhandleClose"
    >
      <z-b-parser
        :form-id="107"
        :is-create="1"
        :edit-data="refundData"
        @submit="refundhandlerSubmit"
        v-if="refundVisible"
        @resetForm="resetFormRefundhandler"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  orderListDataApi,
  orderStatusNumApi,
  orderListApi,
  updatePriceApi,
  orderLogApi,
  orderMarkApi,
  orderPrint,
  orderSendApi,
} from '@/api/order';
import cardsData from '@/components/cards/index';
import detailsFrom from '@/components/orderDetail';
import { storeStaffListApi } from '@/api/storePoint';
import Cookies from 'js-cookie';
import { isWriteOff } from '@/utils';
import { orderExcelApi } from '@/api/store';
import { checkPermi } from '@/utils/permission'; // 权限判断函数
export default {
  name: 'orderlistDetails',
  components: {
    cardsData,
    detailsFrom,
  },
  data() {
    return {
      RefuseVisible: false,
      RefuseData: {},
      orderId: '',
      refundVisible: false,
      refundData: {},
      dialogVisibleJI: false,
      tableDataLog: {
        data: [],
        total: 0,
      },
      tableFromLog: {
        page: 1,
        limit: 10,
        orderNo: 0,
      },
      LogLoading: false,
      isCreate: 1,
      editData: null,
      dialogVisible: false,
      tableData: {
        data: [],
        total: 0,
      },
      listLoading: true,
      tableFrom: {
        status: 'all',
        dateLimit: '',
        orderNo: '',
        page: 1,
        limit: 20,
        type: 0,
      },
      orderChartType: {},
      timeVal: [],
      fromList: this.$constants.fromList,
      fromType: [
        { value: 'all', text: this.$t('quanBu') },
        { value: 'info', text: this.$t('puTong') },
        { value: 'pintuan', text: this.$t('pinTuan') },
        { value: 'bragin', text: this.$t('kanJia') },
        { value: 'miaosha', text: this.$t('miaoSha') },
      ],
      selectionList: [],
      ids: '',
      orderids: '',
      cardLists: [],
      isWriteOff: isWriteOff(),
      proType: 0,
      active: false,
      card_select_show: false,
      checkAll: false,
      checkedCities: [
        'dingDanHao',
        'zhuDingDanHao',
        'dingDanLeiXing',
        'shouHuoRen',
        'shiJiZhiFu',
        'zhiFuFangShi',
        'dingDanZhuangTai',
        'pingTaiBeiZhu',
        'shangJiaBeiZhu',
        'xiaDanShiJian',
      ],
      columnData: [
        'dingDanHao',
        'zhuDingDanHao',
        'dingDanLeiXing',
        'shouHuoRen',
        'shiJiZhiFu',
        'zhiFuFangShi',
        'dingDanZhuangTai',
        'pingTaiBeiZhu',
        'shangJiaBeiZhu',
        'xiaDanShiJian',
      ],
      isIndeterminate: true,
    };
  },
  mounted() {
    this.getList();
    this.getOrderStatusNum();
    // this.getOrderListData();
  },
  methods: {
    checkPermi,
    refundhandleClose() {},
    resetFormRefundhandler() {
      this.refundVisible = false;
    },
    resetFormRefusehand() {
      this.RefuseVisible = false;
    },
    resetForm(formValue) {
      this.dialogVisible = false;
    },
    seachList() {
      this.tableFrom.page = 1;
      this.getList();
      this.getOrderStatusNum();
    },
    // 拒绝退款
    RefusehandleClose() {
      this.RefuseVisible = false;
    },
    // 详情
    onOrderDetails(id) {
      this.orderId = id;
      this.$refs.orderDetail.getDetail(id);
      this.$refs.orderDetail.dialogVisible = true;
    },
    // 订单记录
    onOrderLog(id) {
      this.dialogVisibleJI = true;
      this.LogLoading = true;
      this.tableFromLog.orderNo = id;
      orderLogApi(this.tableFromLog)
        .then((res) => {
          this.tableDataLog.data = res.list;
          this.tableDataLog.total = res.total;
          this.LogLoading = false;
        })
        .catch(() => {
          this.LogLoading = false;
        });
    },
    pageChangeLog(page) {
      this.tableFromLog.page = page;
      this.onOrderLog();
    },
    handleSizeChangeLog(val) {
      this.tableFromLog.limit = val;
      this.onOrderLog();
    },
    handleClose() {
      this.dialogVisible = false;
    },
    // 备注
    onOrderMark(row) {
      this.$prompt(this.$t('dingDanBeiZhu'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        inputErrorMessage: this.$t('qingShuRuDingDanBeiZhu'),
        inputType: 'textarea',
        inputValue: row.platformRemark,
        inputPlaceholder: this.$t('qingShuRuDingDanBeiZhu'),
        inputValidator: (value) => {
          if (!value) return this.$t('shuRuBuNengWeiKong');
        },
      })
        .then(({ value }) => {
          orderMarkApi({ remark: value, orderNo: row.orderNo }).then(() => {
            this.$message.success(this.$t('caoZuoChengGong'));
            this.getList();
          });
        })
        .catch(() => {
          this.$message.info(this.$t('quXiaoShuRu'));
        });
    },
    handleSelectionChange(val) {
      this.selectionList = val;
      const data = [];
      this.selectionList.map((item) => {
        data.push(item.orderNo);
      });
      this.ids = data.join(',');
    },
    // 选择时间
    selectChange(tab) {
      this.timeVal = [];
      this.tableFrom.page = 1;
      this.getList();
      this.getOrderStatusNum();
      // this.getOrderListData();
    },
    // 具体日期
    onchangeTime(e) {
      this.timeVal = e;
      this.tableFrom.dateLimit = e ? this.timeVal.join(',') : '';
      this.tableFrom.page = 1;
      this.getList();
      this.getOrderStatusNum();
      // this.getOrderListData();
    },
    // 列表
    getList() {
      this.listLoading = true;
      orderListApi(this.tableFrom)
        .then((res) => {
          this.tableData.data = res.list || [];
          this.tableData.total = res.total;
          this.listLoading = false;
          this.checkedCities = this.$cache.local.has('order_stroge')
            ? this.$cache.local.getJSON('order_stroge')
            : this.checkedCities;
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    // 数据统计
    getOrderListData() {
      orderListDataApi({ dateLimit: this.tableFrom.dateLimit }).then((res) => {
        this.cardLists = [
          { name: this.$t('dingDanShuLiang'), count: res.count, color: '#1890FF', class: 'one', icon: 'icondingdan' },
          { name: this.$t('dingDanJinE'), count: res.amount, color: '#A277FF', class: 'two', icon: 'icondingdanjine' },
          {
            name: this.$t('weiXinZhiFuJinE'),
            count: res.weChatAmount,
            color: '#EF9C20',
            class: 'three',
            icon: 'iconweixinzhifujine',
          },
          {
            name: this.$t('yuezhiFuJinE'),
            count: res.yueAmount,
            color: '#1BBE6B',
            class: 'four',
            icon: 'iconyuezhifujine2',
          },
        ];
      });
    },
    // 获取各状态数量
    getOrderStatusNum() {
      orderStatusNumApi({ dateLimit: this.tableFrom.dateLimit, type: this.tableFrom.type }).then((res) => {
        this.orderChartType = res;
      });
    },
    pageChange(page) {
      this.tableFrom.page = page;
      this.getList();
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val;
      this.getList();
    },
    exports() {
      let data = {
        dateLimit: this.tableFrom.dateLimit,
        orderNo: this.tableFrom.orderNo,
        status: this.tableFrom.status,
        type: this.tableFrom.type,
      };
      orderExcelApi(data).then((res) => {
        window.open(res.fileName);
      });
    },
    renderHeader(h) {
      return (
        <p>
          <span style="padding-right:5px;">{this.$t('caoZuo')}</span>
          <i class="el-icon-setting" onClick={() => this.handleAddItem()}></i>
        </p>
      );
    },
    handleAddItem() {
      if (this.card_select_show) {
        this.$set(this, 'card_select_show', false);
      } else if (!this.card_select_show) {
        this.$set(this, 'card_select_show', true);
      }
    },
    handleCheckAllChange(val) {
      this.checkedCities = val ? this.columnData : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.columnData.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.columnData.length;
    },
    checkSave() {
      this.$set(this, 'card_select_show', false);
      this.$modal.loading(this.$t('tishi14'));
      this.$cache.local.setJSON('order_stroge', this.checkedCities);
      setTimeout(this.$modal.closeLoading(), 1000);
    },
    //打印小票
    onOrderPrint(data) {
      orderPrint(data.orderNo)
        .then((res) => {
          this.$modal.msgSuccess(this.$t('daYinChengGong'));
        })
        .catch((error) => {
          this.$modal.msgError(error.message);
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.el-table__body {
  width: 100%;
  table-layout: fixed !important;
}
.demo-table-expand {
  ::v-deeplabel {
    width: 83px !important;
  }
}
.refunding {
  span {
    display: block;
  }
}
.selWidth {
  width: 300px;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  font-size: 12px;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.tabBox_tit {
  font-size: 12px !important;
  /*margin: 0 2px 0 10px;*/
  letter-spacing: 1px;
  /*padding: 5px 0;*/
  box-sizing: border-box;
}
.text_overflow {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 400px;
}
.pup_card {
  width: 200px;
  border-radius: 5px;
  padding: 5px;
  box-sizing: border-box;
  font-size: 12px;
  line-height: 16px;
}
.flex-column {
  display: flex;
  flex-direction: column;
}
.mt20 {
  margin-top: 20px;
}
.relative {
  position: relative;
}
.card_abs {
  position: absolute;
  padding-bottom: 15px;
  top: 340px;
  right: 40px;
  width: 200px;
  background: #fff;
  z-index: 99999;
  box-shadow: 0px 0px 14px 0px rgba(0, 0, 0, 0.1);
}
.cell_ht {
  height: 50px;
  padding: 15px 20px;
  box-sizing: border-box;
  border-bottom: 1px solid #eeeeee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.check_cell {
  width: 100%;
  padding: 15px 20px 0;
}
::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #606266;
}
</style>
